<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表--
		 @row-click="activeDrawer" 行单击事件，activeDrawer（row）row表示当前行数据（规定死的）-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;"

		>
			<!--employeeForm: {
		            id: null,
                    username: "",
                    email: "",
                    phone: 0,
                    age: 0,
                    state:0
				},-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="120" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="180" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="180" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="100" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="150" sortable>
				<!-- 后台传过来的是Integer值，需要在前端判断启用状态 -->
				<template scope="scope">
					<span style="color: gold" v-if="scope.row.state === 1">启用</span>
					<span style="color:crimson" v-else-if="scope.row.state === 0">禁用</span>
					<span style="color:gray" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="salt" label="盐值" width="200" sortable>
			</el-table-column>
			<el-table-column prop="password" label="密码" width="200" sortable>

			</el-table-column>
			<el-table-column prop="shop.name" label="店铺" width="200" sortable>

			</el-table-column>
			<!--<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级员工" width="180" sortable>
			</el-table-column>-->
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<!--<el-button type="success" size="small" >子项</el-button>-->
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" >批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<!--
		            id: null,
                    username: "",
                    email: "",
                    phone: 0,
                    age: 0,
		-->
		<el-dialog :title="title" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm" >
				<!--prop="name"  申明表单中有一个属性name-->
				<el-form-item label="姓名" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电子邮件" prop="email">
					<el-input v-model="employeeForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="employeeForm.age" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="盐值" prop="salt">
					<el-input v-model="employeeForm.salt" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="employeeForm.password" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>



				<el-form-item label="上级部门">
					<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
					<!--:label 选择后展示在选择框中的内容
						   :value 选择后你要传送给后端的值-->
					<el-cascader v-model="employeeForm.department"
								 clearable
								 :options="departmentsTree"
								 :props="{
							   checkStrictly: true,
							   label: 'name',
							   value: 'id'
							}">
					</el-cascader>
				</el-form-item>
				<el-form-item label="店铺">
					<!--<el-input v-model="departmentForm.manager" auto-complete="off"></el-input>-->
					<el-select v-model="employeeForm.shop" clearable value-key="id" placeholder="请选择">
						<!--
						   clearable  可清空
						   <
						   v-for="遍历的data对象"
						   el-option  : 选项
						   :label 选择后展示在选择框中的内容
						   :value 选择后你要传送给后端的值
						-->
						<el-option
								v-for="item in shops"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.id}}</span>
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="employeeFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="employeeSubmit" :loading="employeeLoading">提交</el-button>
			</div>

		</el-dialog>

<!--
		不想动员工当前布局了
<el-drawer
				title="抽屉测试"
				:visible.sync="drawer"
				:direction="direction"

		>
		</el-drawer>-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, employeeEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
			return {
                drawer: false,
                direction: 'rtl',
				filters: {
                    keyword: ''
				},
                title:"",
                employees: [],
				employeesTree:[],
				departments:[],
                departmentsTree:[],
                shops:[],
				total: 0,
				page: 1,
                pageSize: 10,
				listLoading: false,
				sels: [],//列表选中列

				employeeFormVisible: false,//编辑界面是否显示
				employeeLoading: false,
				employeeFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				employeeForm: {
                    id: null,
                    username: "",
                    email: "",
					salt:"",
                    phone: "",
                    age: 0,
					state: 1,
					department:null,
                    department_id:null,
					shop:null,
					shop_id:null
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    //验证规则
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
			}
		},
		methods: {
		    /*activeDrawer(row){
		        this.drawer = true;
		        alert(row.id);
		        //alert("触发了单击事件");
		        //console.log("触发了打印到控制台");
			},*/
/*            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        this.drawer = false;
                        done();
                    })
                    .catch(_ => {});
            },*/
            search(){
		        this.page = 1;
                this.getEmployee();
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getEmployee();
			},
			//员工列表
			getEmployee() {
				let para = {
					currentPage: this.page,
                    keyword: this.filters.keyword,
                    pageSize:this.pageSize
				};
				this.$http.post("/employee",para)
					.then(result=>{
					    //alert("请求成功有数据")
						result = result.data;//PageList{count employeelist}
						console.log(result);// 看看数据到这里没有
						this.employees = result.list;
						this.total = result.count;
					})
					.catch(result=>{
					    console.log(result);
					})
			},
            getDepartmentTree(){
                this.$http.get("/dept/tree")
                    .then(result=>{
                        result = result.data;
                        this.departmentsTree = result;

                    })
            },
            getDepartments() {
                this.$http.get("/dept")
                    .then(result=>{
                        //alert("请求成功有数据")
                        console.log(result);// 看看数据到这里没有
                        this.departments = result.data;
                    })
                    .catch(result=>{
                        console.log(result);
                    })
            },
            getShops() {
                this.$http.get("/shop")
                    .then(result=>{
                        //alert("请求成功有数据")
                        console.log(result);// 看看数据到这里没有
                        this.shops = result.data;
                    })
                    .catch(result=>{
                        console.log(result);
                    })
            },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/employee/"+para.id)
						.then(result=>{
						    result = result.data;
						    if (result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;
                                this.getEmployee();
                                //this.getEmployee();
							} else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
							}
						})
						.catch(result=>{
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
						})
                    this.listLoading = false;

                }).catch(() => {
				});


            },
			//显示编辑界面
			handleEdit: function (index, row) {
                // 只能显示两级（选择框限制）
                this.getDepartmentTree();
			    this.title="编辑";
				this.employeeFormVisible = true;
				this.employeeForm = Object.assign({}, row);
				if (this.employeeForm.department != null){
                    let parentpath = [];
					let ps = this.employeeForm.department.dirPath.split("/");
					console.log(ps);
					for (let i=1;i<ps.length;i++){
						parentpath.push(parseInt(ps[i]));
					}
					console.log(parentpath);
					this.employeeForm.department = parentpath;
				}


			},
			//显示新增界面
			handleAdd: function () {
                this.getDepartmentTree();
                this.title="添加";
				this.employeeFormVisible = true;
				// 清空表单，否则关闭编辑界面后数据会保留
				this.employeeForm = {
                    id: null,
                    username: "",
                    email: "",
                    phone: null,
                    age: null,
                    department_id:null
                };
			},
			//编辑
			employeeSubmit: function () {
				this.$refs.employeeForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.employeeLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.employeeForm);
							if (para.department){
							    let pids = para.department;
							    let pid = pids[pids.length-1];
							    para.department = {"id":pid};
                                para.department_id = pid;
							}
							this.$http.put("/employee",para)
								.then(result=>{
								    result = result.data;
									if (result.success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        this.employeeLoading = false;
                                        this.employeeFormVisible = false;
                                        this.getEmployee();
									} else {
                                        this.employeeLoading = false;//关闭忙等框
                                        this.$message({
                                            message: '操作失败',
                                            type: 'error'
                                        });
									}
								})
								.catch(result=>{
                                    this.employeeLoading = false;//关闭忙等框
                                    this.$message({
                                        message: '操作失败',
                                        type: 'error'
                                    });
								})

						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				//alert(ids);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();

                    this.$http.patch("/employee",ids)
                        .then(result=>{
                            result = result.data;
                            if (result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: '删除失败',
                                    type: 'error'
                                });
                            }
                            this.page = 1;
                            this.getEmployee();
                        })
                        .catch(result=>{
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                            this.page = 1;
                            this.getEmployee();
                        })

                    this.listLoading = false;
				}).catch(() => {

				});
			},


		},

		mounted() {
			this.getEmployee();
            this.getDepartments();
            this.getShops();
		}
	}

</script>

<style scoped>


</style>